<?php

namespace App\Listeners;

use App\Events\MessageActionVote;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use App\Models\Group;
use App\Models\User;

class NotificationMessageActionVote
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  MessageVote  $event
     * @return void
     */
    public function handle(MessageActionVote $event)
    {
        $message = $event->message;

        if($message->message_type=='post'){//朋友圈投票或取消

            $to = $message->to()->first();
            $user = request()->user()??null;
            if(!$to->users()->where('id',optional($user)->id)->first()){//点赞用户是否已经加入朋友圈的群聊
                $to->users()->syncWithoutDetaching([$user->id]);

                $selfGroup = Group::where('user_to_user', $user->id.'-'.$user->id)->first();
                if($selfGroup){//发送给自己
                    event(new \App\Events\RefreshUser($selfGroup->id));
                    // event(new \App\Events\MessageReplace($selfGroup->id,$message));//通知自己替换消息
                    // sleep(1);//等刷新完成，才能替换消息
                }else{
                    \Log::info($message->id,[
                        'action'=>'post vote',
                        'msg'=>'找不到自己的聊天',
                        'code'=>1,
                        'data' =>[
                            'message_id'=> $message->id
                        ]
                    ]);
                }

            }else{//已经加入过

            }

            //一个一个通知 该朋友圈的好友,这样进入朋友圈的用户可以收到动态消息

            $postUser = User::find($message->from_id);

            if($postUser){
                $friendUGroupIds = $postUser->getFriendGroupIds();
                foreach ($friendUGroupIds as $friendUGroupId){
                    event(new \App\Events\MessageReplace($friendUGroupId,$message));//通知朋友圈替换消息
                }   
            }

        }else{//其他消息点赞
            event(new \App\Events\MessageReplace($message->to_id,$message));//通知群里替换消息
        }





    }
}
